package com.chunuo.gulimall.product.service.impl;

import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.chunuo.gulimall.product.entity.CategoryBrandRelationEntity;
import com.chunuo.gulimall.product.service.CategoryBrandRelationService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.Map;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.chunuo.common.utils.PageUtils;
import com.chunuo.common.utils.Query;

import com.chunuo.gulimall.product.dao.BrandDao;
import com.chunuo.gulimall.product.entity.BrandEntity;
import com.chunuo.gulimall.product.service.BrandService;
import org.springframework.transaction.annotation.Transactional;

@Slf4j
@Service("brandService")
public class BrandServiceImpl extends ServiceImpl<BrandDao, BrandEntity> implements BrandService {

    @Autowired
    private CategoryBrandRelationService categoryBrandRelationService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        QueryWrapper<BrandEntity> wrapper = new QueryWrapper<>();

        String key = (String) params.get("key");
        if(!key.isEmpty()){
            wrapper.and((obj)->{
                obj.eq("brand_id",key).or().like("name",key);
            });
        }

        IPage<BrandEntity> page = this.page(
                new Query<BrandEntity>().getPage(params),
                wrapper
        );

        return new PageUtils(page);
    }

    @Transactional
    @Override
    public void updateDetail(BrandEntity brand) {
        this.updateById(brand);
        log.info("brand {}",brand);
        UpdateWrapper<CategoryBrandRelationEntity> wrapper =  new UpdateWrapper<>();
        wrapper.eq("brand_id",brand.getBrandId()).set("brand_name",brand.getName());
        categoryBrandRelationService.update(wrapper);

    }

}